package cn.micai.base.lambda;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * 描述：Java 8 Lambda : Comparator example
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/21 14:08
 */
public class ComparatorSortingExample {

    public static void main(String [] args) {

        List<Developer> developerList = getDevelopers();

        System.out.println("Before Sort");
        for (Developer developer : developerList) {
            System.out.println(developer);
        }

        // sort by age
        /*Collections.sort(developerList, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getAge() - o2.getAge();
            }
        });*/

        // sort by name
        /*Collections.sort(developerList, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });*/

        // sort by salary
        /*Collections.sort(developerList, new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getSalary().compareTo(o2.getSalary());
            }
        });*/

        // List.sort() since Java 8
        /*developerList.sort(new Comparator<Developer>() {
            @Override
            public int compare(Developer o1, Developer o2) {
                return o1.getAge()-o2.getAge();
            }
        });*/

        // lambda here
        /*developerList.sort((Developer o1, Developer o2)->o1.getAge()-o2.getAge());*/
        /*developerList.sort((Developer o1, Developer o2) -> o1.getName().compareTo(o2.getName()));*/
        /*developerList.sort((Developer o1, Developer o2)->o1.getSalary().compareTo(o2.getSalary()));*/

        // lambda, valid, parameter type is optional
        developerList.sort((o1, o2) -> o1.getAge()-o2.getAge());

        System.out.println("After Sort");

        // java 8 only, lambda also, to print the list
        developerList.forEach((developer -> System.out.println(developer)));

        /*for (Developer developer : developerList) {
            System.out.println(developer);
        }*/

    }

    private static List<Developer> getDevelopers() {
        List<Developer> developerList = new ArrayList<>();

        developerList.add(new Developer("mkyong", new BigDecimal("70000"), 33));
        developerList.add(new Developer("alvin", new BigDecimal("80000"), 20));
        developerList.add(new Developer("iris", new BigDecimal("170000"), 55));
        developerList.add(new Developer("jason", new BigDecimal("100000"), 10));

        return developerList;

    }
}
